﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace Cms.Web.Images
{
    /// <summary>
    /// 专门处理图标用
    /// </summary>
    public class Icon : IHttpHandler
    {
        private static Dictionary<int, string> _Icons = null;
        private static object lockobject = new object();
        private static Dictionary<int, string> Icons
        {
            get {
                if (_Icons == null) {
                    lock (lockobject) {
                        _Icons = new Dictionary<int, string>();
                    }
                }
                return _Icons;
            }
            set {
                _Icons = value;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/css";
            int size = EntLib.Request.GetInt("size", 16);
            string cssContent = CssBuilder(context, size);
            context.Response.Expires = 60;
            context.Response.Write(cssContent);
            context.Response.End();
        }
        public string CssBuilder(HttpContext context, int size)
        {
            if (Icons.ContainsKey(size)) {
                return Icons[size];
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                string imgPath = context.Server.MapPath(String.Format("~/Images/Icon/{0}", size));
                if (System.IO.Directory.Exists(imgPath) && !Icons.ContainsKey(size))
                {
                    string imgShortPath = String.Format("Icon/{0}/", size);
                    string spritePath = context.Server.MapPath(String.Format("~/Images/Icon/", size));
                    EntLib.ImageMerge imgMerge = new EntLib.ImageMerge(imgPath, 16, 16, true, spritePath + "\\sprite_16_16.png");
                    imgMerge.CreateSprite();
                    string css = imgMerge.BuilderCss(".icon{0},.ztree li span.button.icon{0}_ico_docu,.tabs-icon.icon{0}", "Icon/sprite_16_16.png");
                    sb.Append(css);
                    if(Icons.ContainsKey(size))
                        Icons.Add(size, css);
                }
                return sb.ToString();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}